"""
 Copyright CUBE Gestioni S.r.l. 2010

 Base configuration and imports for all model parts
 - common functions
 - qbClass
 - Inherited

 $Id: sqlbase.py 431 2011-06-29 15:35:41Z andre $

"""
# from cubemail import meta
from sqlalchemy import schema, types, orm, join, desc, and_
from sqlalchemy.orm import validates

import meta
import formatter as f


# # Common Functions
# def now():
    # return DateTime(notz=True)

# *************************************************************************** #

class qbClass(object):
    """
    @class qbClass
    @brief Class with methods for JSON, XML, CSV and HTML formatting and some commodities
    """

    @classmethod
    def all(cls, order_by=None, filter_on=None):
        """ get all records """
        q=meta.session.query(cls)
        if order_by:
            q=q.order_by(order_by)
        if filter:
            q=q.filter(filter_on)
        return q.all()

    @classmethod
    def get(cls, pkid):
        """ get by id """
        return meta.session.query(cls).get(pkid)

    @classmethod
    def byLabel(cls, label):
        """ get by label """
        return meta.session.query(cls).filter(cls.__dict__['label'] == unicode(label).upper()).first()


    ## Formatters
    # JSON
    JsonItem = f.JsonItem
    @classmethod
    def Json(cls): return f.Json(cls.all())

    # CSV
    CsvItem  = f.CsvItem
    @classmethod
    def Csv(cls): return f.Csv(cls.all())

    # XML
    XmlItem  = f.XmlItem
    @classmethod
    def Xml(cls): return f.Xml(cls.all())

    # General
    formatItem = f.formatItem
    @classmethod
    def format(cls, format='json', withHeader=False): return f.format(cls.all(), format=format, withHeader=withHeader)

